package com.mango.community.controller;

import com.mango.community.annotation.LoginRequired;
import com.mango.community.entity.User;
import com.mango.community.service.FollowService;
import com.mango.community.service.LikeService;
import com.mango.community.service.UserService;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.CommunityUtil;
import com.mango.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/25 17:18
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 注入域名
     */
    @Value("${community.path.domain}")
    private  String domain;
    /**
     * 上传的我图片的路径
     */
    @Value("${community.path.upload}")
    private String uploadPath;
    /**
     * 注入项目名
     */
    @Value("${server.servlet.context-path}")
    private  String contextPath;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(){
        return "/site/setting";
    }

    /** 上传文件
     * MultipartFile SpringMVC提供的专门上传文件的属性
     * @param headerImg
     * @param model
     * @return
     */
    @LoginRequired
    @PostMapping("/upload")
    private String uploadHeader(MultipartFile headerImg , Model model){
        if(headerImg == null ){
            model.addAttribute("error","你没有选择图片!");
            return "/site/setting";
        }
        //得到上传文件的原始文件名
        String filename = headerImg.getOriginalFilename();
        //从最后一个 . 的索引后的所有都截取到就是后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //判断后缀是否合法
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件的格式不正确!");
            return "/site/setting";
        }
        //生成随机的文件名
        filename = CommunityUtil.generateUUID() + suffix;
        //确定文件存放的路径
        File dest = new File(uploadPath + "/" + filename);
        try {
            //将文件内容（图片）写入到目标路径
            headerImg.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw  new RuntimeException("上传文件失败，服务器异常!" + e);
        }
        //更新当前用户的头像路径（web的访问路径）
        //获取当前用户
        User user = hostHolder.getUser();
        //动态的拼接用户头像的访问路径
        //参考路径  http://localhost:8080/community/user/header/xxxxx
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        //更新用户头像的访问地址
        userService.updateHeader(user.getId(),headerUrl);
        //头像更新成功后重定向到首页
        return "redirect:/index";
    }

    /**  获取用户的头像，因为图片是二进制流的形式，所以不用返回值，使用response手动写出去
     * @param fileName
     * @param response
     */
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器存放图片的路径
        fileName = uploadPath + "/" + fileName;
        //解析图片文件的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/"+suffix);
        try(   //jdk1.7 的新特性，在这里写有需要关闭的他会自动关闭
                //创建文件的输入流
            FileInputStream inputStream = new FileInputStream(fileName);
            ) {
            //用response获取字节流
            OutputStream outputStream = response.getOutputStream();
            //创建一个缓冲区
            byte[] buffer = new byte[1024];
            //创建一个游标
            int b =0 ;
            //循环获取字节
            while ((b=inputStream.read(buffer)) != -1){
                //当不等于 -1 时向外写数据  从0 写道 b
                outputStream.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getMessage());
        }
    }

    @LoginRequired
    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword,String newPassword,Model model){
        int userId=hostHolder.getUser().getId();
        if(oldPassword.equals(newPassword)){
            model.addAttribute("password","两次输入的密码不一致！");
            return "/site/setting";
        }
        Map<String, Object> map = userService.updatePassword(userId, oldPassword, newPassword);
        //如果map中存在passwordMsg 证明密码修改有错误
        if(map.containsKey("oldPasswordMsg")||map.containsKey("newPasswordMsg")){
            model.addAttribute("oldPasswordMsg",map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg",map.get("newPasswordMsg"));
            model.addAttribute("newPassword",newPassword);
            model.addAttribute("oldPassword",oldPassword);
            return "/site/setting";
        }
        model.addAttribute("newPasswordMsg","密码修改成功!");
        return "redirect:/index";
    }

    /** 个人主页
     * @param userId 用户的id
     * @param model
     * @return
     */
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId")int userId,Model model){
        User user = userService.findUserById(userId);
        //查询用户是否存在
        if(user == null){
            throw new RuntimeException("该用户不存在!");
        }
        //用户的基本信息
        model.addAttribute("user",user);
        //用户获赞的数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        //查询关注的数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //查询粉丝的数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount",followerCount);
        //查询是否已关注
        boolean hasFollowed = false;
        //当前用户必须时登录状态
        if(hostHolder.getUser() != null){
                hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        //返回用户的个人页面
        return "/site/profile";
    }
}
